﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Pageparkproject.Models;
using PagedList;
using System.IO;

namespace Pageparkproject.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        AdminStories Story = new AdminStories();
        public string getRandomIntName()
        {
            Random rd = new Random();
            string name = rd.Next(int.MaxValue).ToString()+rd.Next(int.MaxValue).ToString()+rd.Next(int.MaxValue).ToString();
            return name;
        }
        public ActionResult Index()
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login","Admin");
            }
            return View();
        }
        #region [Login,Logout]
        public bool isLogin()
        {
            if (Session != null && Session["username"] != null)
            {
                return true;
            }
            return false;
        }
        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(FormCollection Fc)
        {
            String username = Fc["username"].ToString();
            String password = Fc["password"].ToString();
            if (Story.loginAdmin(username, password,Request.UserHostAddress) == true)
            {
                Session.Add("username", username);
                Session.Add("name", Story.adminFindByUsername(username).sName);
                if (Session != null && Session["LastUrl"] != null)
                {
                    string url = Session["LastUrl"].ToString();
                    Session.Remove("LastUrl");
                    return Redirect(url);
                }
                else return RedirectToAction("Index", "Admin");
            }
            else
            {
                ViewBag.Ms = "Tên đăng nhập không tồn tại hoặc Mật khẩu không chính xác";
            }
            return View();
        }
        public ActionResult Logout()
        {
            Session.RemoveAll();
            return RedirectToAction("Login","Admin");
        }
        #endregion
        #region [Manage Project]
        public ActionResult ProjectManage(int ?page)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            int pageNumber,pageSize;
            pageNumber = (page ?? 1);
            pageSize = 12;
            return View(Story.projectList().ToPagedList(pageNumber,pageSize));
        }

        public class img {
            public int id {get;set;}
            public string images { get; set; }
        }

        public JsonResult projectGetById(int id)
        {
            var project = Story.projectGetById(id);
            List<img> listImg = new List<img>();
            foreach (var item in project.tblImageProjects.ToList())
            {
                listImg.Add(new img(){id=item.PK_iImageID,images=item.sImages  });
            }
            string projectName = project.sProjectName;
            string sAnh = project.sAnh;
            string projectDescription = project.sDescription;
            bool status = project.bStatus;
            int categoryId = project.FK_iCategoryID;
            int projectId = project.PK_iProjectID;
            string projectDate = project.dNgay.ToShortDateString();
            var response = new { sAnh=sAnh,projectId = projectId, categoryId=categoryId,projectName=projectName,projectDescription=projectDescription,status=status,projectDate=projectDate,listImg=listImg};
            return Json(response,JsonRequestBehavior.AllowGet);
        }

        public JsonResult categoryGetSelectList()
        {
            return Json(Story.categoryGetSelectList(), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ProjectCreate(tblProject item,HttpPostedFileBase file,HttpPostedFileBase[] files)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            if (file!=null)
            {
                var fileName = Path.GetFileName(file.FileName);
                string newname = getRandomIntName();
                var path = Path.Combine(Server.MapPath("~/Contents/Images/Project"), newname + ".jpg");
                file.SaveAs(path);
                item.sAnh = newname + (".jpg");
            }
            Story.projectCreate(item);
            foreach (var itemfile in files)
            {
                if (itemfile != null)
                {
                    tblImageProject img = new tblImageProject();
                    img.FK_iProjectID=item.PK_iProjectID;
                    img.sImages="Noname";
                    img.sTitle=item.sProjectName;
                    Story.imagesProjectCreate(img);
                    var fileName = Path.GetFileName(itemfile.FileName);
                    string newname = item.PK_iProjectID.ToString()+img.PK_iImageID.ToString();
                    var path = Path.Combine(Server.MapPath("~/Contents/Images/Project"), newname + ".jpg");
                    itemfile.SaveAs(path);
                    img.sImages =  newname + ".jpg";
                    Story.imagesProjectEditName(img);
                }
            }
            return RedirectToAction("ProjectManage");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ProjectEdit(tblProject item,HttpPostedFileBase file, HttpPostedFileBase[] files)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            if (file != null)
            {
                var fileName = Path.GetFileName(file.FileName);
                string newname = getRandomIntName();
                var path = Path.Combine(Server.MapPath("~/Contents/Images/Project"), newname + ".jpg");
                file.SaveAs(path);
                item.sAnh = newname + (".jpg");
            }
            Story.projectEdit(item);
            if (files != null)
            {
                foreach (var itemfile in files)
                {
                    if (itemfile != null)
                    {
                        tblImageProject img = new tblImageProject();
                        img.FK_iProjectID = item.PK_iProjectID;
                        img.sImages = "Noname";
                        img.sTitle = item.sProjectName;
                        Story.imagesProjectCreate(img);
                        var fileName = Path.GetFileName(itemfile.FileName);
                        string newname = item.PK_iProjectID.ToString() + img.PK_iImageID.ToString();
                        var path = Path.Combine(Server.MapPath("~/Contents/Images/Project"), newname + ".jpg");
                        itemfile.SaveAs(path);
                        img.sImages = newname + ".jpg";
                        Story.imagesProjectEditName(img);
                    }
                }
            }
            return RedirectToAction("ProjectManage");
        }

        public ActionResult ProjectDelete(int id)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            Story.projectDelete(id);
            return RedirectToAction("ProjectManage");
        }

        [HttpPost]
        public JsonResult ProjectImagesDelete(int id)
        {
            Story.imagesProjectDelete(id);
            return Json(true);
        }
        #endregion
        #region [Manage News]
        public JsonResult getListCategoryNews()
        {
            return Json(Story.getListCategoryNews(), JsonRequestBehavior.AllowGet);
        }
        public ActionResult NewsManage(int ?page)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            int pageNumber, pageSize;
            pageNumber = (page ?? 1);
            pageSize = 12;
            return View(Story.newsList().ToPagedList(pageNumber, pageSize));
        }

        public JsonResult newsGetById(int id)
        {
            var item = Story.newsGetById(id);
            string sTieude = item.sTieude;
            string sTomtat = item.sTomtat;
            bool status = item.bStatus;
            string sNoidung = item.sNoidung;
            int PK_iNewsID = item.PK_iNewsID;
            string dDatepost = item.dDatepost.ToString();
            string sAnh = item.sAnh;
            int? FK_iCategoryNewsID = item.FK_iCategoryNewsID;
            var response = new { sTieude=sTieude,sTomtat=sTomtat,status=status,sNoidung=sNoidung,PK_iNewsID=PK_iNewsID,dDatepost=dDatepost,sAnh=sAnh,FK_CategoryNewsID=FK_iCategoryNewsID };
            return Json(response, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult NewsCreate(tblNew item, HttpPostedFileBase files)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            Story.newsCreate(item);
                if (files != null)
                {
                    var fileName = Path.GetFileName(files.FileName);
                    string newname ="News"+ item.PK_iNewsID.ToString();
                    var path = Path.Combine(Server.MapPath("~/Contents/Images/News"), newname + ".jpg");
                    files.SaveAs(path);
                    item.sAnh = newname + ".jpg";
                    Story.newsEdit(item);
                }
            return RedirectToAction("NewsManage");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult NewsEdit(tblNew item, HttpPostedFileBase files)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            Story.newsEdit(item);
            if (files != null)
            {
                var fileName = Path.GetFileName(files.FileName);
                string newname = "News" + item.PK_iNewsID.ToString();
                var path = Path.Combine(Server.MapPath("~/Contents/Images/News"), newname + ".jpg");
                files.SaveAs(path);
                item.sAnh = newname + ".jpg";
                Story.newsEdit(item);
            }
            return RedirectToAction("NewsManage");
        }

        public ActionResult NewsDelete(int id)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            Story.newsDelete(id);
            return RedirectToAction("NewsManage");
        }
        #endregion
        #region [Log]
        public ActionResult Log(int ?page)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            int pageNumber, pageSize;
            pageNumber = (page ?? 1);
            pageSize = 40;
            return View(Story.logList().ToPagedList(pageNumber, pageSize));
        }
        #endregion
        #region [Manage Category]
        public ActionResult CategoryManage(int ?page)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            int pageNumber, pageSize;
            pageNumber = (page ?? 1);
            pageSize = 12;
            return View(Story.categoryList().ToPagedList(pageNumber, pageSize));
        }

        public JsonResult categoryGetById(int id)
        {
            var item = Story.categoryGetById(id);
            int PK_iCategoryID = item.PK_iCategoryID;
            string sCategoryName = item.sCategoryName;
            bool status = item.bStatus;
            var response = new { PK_iCategoryID=PK_iCategoryID,sCategoryName=sCategoryName,status=status };
            return Json(response, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult CategoryCreate(tblCategory item)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            Story.categoryCreate(item);
            return RedirectToAction("CategoryManage");
        }

        [HttpPost]
        public ActionResult CategoryEdit(tblCategory item)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            Story.categoryEdit(item);
            return RedirectToAction("CategoryManage");
        }

        public ActionResult CategoryDelete(int id)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            Story.categoryDelete(id);
            return RedirectToAction("CategoryManage");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        ///   
        public ActionResult CategoryNewsManage(int? page)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            int pageNumber, pageSize;
            pageNumber = (page ?? 1);
            pageSize = 12;
            return View(Story.categoryNewsList().ToPagedList(pageNumber, pageSize));
        }

        public JsonResult categoryNewsGetById(int id)
        {
            var item = Story.categoryNewsGetById(id);
            int PK_iCategoryNewsID = item.PK_iCategoryNewsID;
            string sCategoryName = item.sCategoryName;
            bool status = item.bStatus;
            var response = new { PK_iCategoryNewsID = PK_iCategoryNewsID, sCategoryName = sCategoryName, status = status };
            return Json(response, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult CategoryNewsCreate(tblCategoryNew item)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            Story.categoryNewsCreate(item);
            return RedirectToAction("CategoryNewsManage");
        }

        [HttpPost]
        public ActionResult CategoryNewsEdit(tblCategoryNew item)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            Story.categoryNewsEdit(item);
            return RedirectToAction("CategoryNewsManage");
        }

        public ActionResult CategoryNewsDelete(int id)
        {
            if (!isLogin())
            {
                if (Request.UrlReferrer != null)
                {
                    Session.Add("LastUrl", Request.UrlReferrer.OriginalString.ToString());
                }
                return RedirectToAction("Login", "Admin");
            }
            Story.categoryNewsDelete(id);
            return RedirectToAction("CategoryNewsManage");
        }
        #endregion
        #region [Setting]

        public ActionResult Setting()
        {
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveSetting(tblSetting item, HttpPostedFileBase fileIndex1, HttpPostedFileBase fileIndex2, HttpPostedFileBase fileIndex3, HttpPostedFileBase fileIndex4, HttpPostedFileBase fileIndex5, HttpPostedFileBase fileAbout)
        {
            if (fileIndex1 != null)
            {
                string name = "index1";
                var path = Path.Combine(Server.MapPath("~/Contents/Images"), name + ".jpg");
                fileIndex1.SaveAs(path);
            }
            if (fileIndex2 != null)
            {
                string name = "index2";
                var path = Path.Combine(Server.MapPath("~/Contents/Images"), name + ".jpg");
                fileIndex2.SaveAs(path);
            }
            if (fileIndex3 != null)
            {
                string name = "index3";
                var path = Path.Combine(Server.MapPath("~/Contents/Images"), name + ".jpg");
                fileIndex3.SaveAs(path);
            }
            if (fileIndex4 != null)
            {
                string name = "index4";
                var path = Path.Combine(Server.MapPath("~/Contents/Images"), name + ".jpg");
                fileIndex4.SaveAs(path);
            }
            if (fileIndex5 != null)
            {
                string name = "index5";
                var path = Path.Combine(Server.MapPath("~/Contents/Images"), name + ".jpg");
                fileIndex5.SaveAs(path);
            }
            if (fileAbout != null)
            {
                string name = "about";
                var path = Path.Combine(Server.MapPath("~/Contents/Images"), name + ".jpg");
                fileAbout.SaveAs(path);
            }
            Story.SettingEdit(item);
            return Content("Lưu thành công!");
        }
        [HttpGet]
        public JsonResult getSetting()
        {
            var setting = Story.getSetting();
            var res = new { 
                            sWebName = setting.sWebName,
                            fLatitude = setting.fLatitude,
                            fLongtitude = setting.fLongtitude,
                            sContentFooter=setting.sContentFooter,
                            sGioithieu = setting.sGioithieu,
                            sImageGioithieu = setting.sImageGioithieu,
                            sImageIndex = setting.sImageIndex,
                            sContact = setting.sContact,
                            sColorBar = setting.sColorBar
            };
            return Json(res,JsonRequestBehavior.AllowGet);
        }

        public PartialViewResult EditSetting()
        {
            return PartialView(Story.getSetting());
        }

        [ChildActionOnly]
        public PartialViewResult TableSetting()
        {
            return PartialView(Story.getSetting());
        }

        public PartialViewResult FormProject()
        {
            return PartialView();
        }
        #endregion
        #region []
        #endregion
        #region []
        #endregion
        #region []
        #endregion
        #region []
        #endregion
        #region []
        #endregion
        #region []
        #endregion
        #region []
        #endregion
        #region []
        #endregion
        #region []
        #endregion
        #region []
        #endregion
    }
}
